//index.js
//获取应用实例
var QR = require("../../utils/qrcode.js");
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    buttonHidden: false
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    // 读取用户信息
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else {
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }

    // 发送加密的数据到服务器端来获取unionId

    // 让用户选择是司机还是乘客
    if (!wx.getStorageSync('isDrive')) {
      
    } else {
      this.setData({
        buttonHidden: true
      })
      this.createQRCode()
    }
  },
  // 我是司机按钮事件
  isDriverClick: function(e) {
    wx.setStorageSync('isDrive','1')
    this.setData({
      buttonHidden: true
    })
    this.createQRCode()
  },
  // 我是乘客按钮事件
  isPassengerClick: function(e) {
    wx.setStorageSync('isDrive','0')
    this.setData({
      buttonHidden: true
    })
    this.createQRCode()
  },
  // 生成二维码
  createQRCode: function() {
    // 页面初始化 options为页面跳转所带来的参数
    var size = this.setCanvasSize();//动态设置画布大小
    this.createQrCode(wx.getStorageSync('isDrive'), "mycanvas", size.w, size.h);
  },
  //适配不同屏幕大小的canvas
  setCanvasSize:function(){
    var size={};
    try {
        var res = wx.getSystemInfoSync();
        var scale = 750/686;//不同屏幕下canvas的适配比例；设计稿是750宽
        var width = res.windowWidth/scale;
        var height = width;//canvas画布为正方形
        size.w = width;
        size.h = height;
      } catch (e) {
        // Do something when catch error
        console.log("获取设备信息失败"+e);
      } 
    return size;
  } ,
  createQrCode:function(url,canvasId,cavW,cavH){
    //调用插件中的draw方法，绘制二维码图片
    QR.api.draw(url,canvasId,cavW,cavH);
    setTimeout(() => { this.canvasToTempImage();},1000);
    
  },
  //获取临时缓存照片路径，存入data中
  canvasToTempImage:function(){
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      success: function (res) {
          var tempFilePath = res.tempFilePath;
          console.log(tempFilePath);
          that.setData({
              imagePath:tempFilePath,
             // canvasHidden:true
          });
      },
      fail: function (res) {
          console.log(res);
      }
    });
  },
})
